import { reactive } from "vue";
import { me, changePwd, changeAnswer } from "@/api/auth/user";
import { ElMessage } from "element-plus";

export const _$ = reactive({
  requestParam: {
    id: null,
    oldPwd: "",
    newPwd: "",
    confirPwd: "",
    question: "",
    answer: "",
  },
  responseParam: {},
  rules: reactive({}),
});

export const $ = {
  async onSubmit(formEl) {
    if (!formEl) {
      return;
    }
    await formEl.validate((valid, fields) => {
      if (valid) {
        if (_$.requestParam.newPwd !== _$.requestParam.confirPwd) {
          ElMessage({
            message: "密码与确认密码不一致",
            type: "warning",
          });
          return;
        }
        changePwd(_$.requestParam).then((_) => {
          ElMessage({
            message: "修改成功",
            type: "success",
          });
        });
      }
    });
  },

  async onSubmitModifyQuestion(formEl) {
    if (!formEl) {
      return;
    }
    await formEl.validate((valid, fields) => {
      if (valid) {
        changeAnswer(_$.requestParam).then((_) => {
          ElMessage({
            message: "修改成功",
            type: "success",
          });
        });
      }
    });
  },

  loadEdit() {
    me().then((data) => {
      _$.requestParam = data;
      _$.requestParam.question = "";
      _$.requestParam.answer = "";
    });
  },

  clean() {
    _$.requestParam = {
      oldPwd: "",
      newPwd: "",
      confirPwd: "",
      question: "",
      answer: "",
    };
  },
};

export const to = {};
